package com.leo.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName IOServer
 * @Description
 * @Author wangss
 * @date 2022.03.17 20:12
 * @Version 1.0
 */
public class IOServer {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8000);

        // 接收连接线程
        new Thread(() -> {
            System.out.println("1 ------- " + Thread.currentThread().getName());
            while (true) {
                try {
                    // 阻塞方法获取新连接
                    Socket socket = serverSocket.accept();

                    // 为每个连接都创建一个新线程，负责读取数据
                    new Thread(() -> {
                        try {
                            System.out.println("2 ------- " + Thread.currentThread().getName());
                            int len;
                            byte[] data = new byte[1024];
                            InputStream inputStream = socket.getInputStream();
                            System.out.println("3 ------- " + Thread.currentThread().getName());
                            // 这里会一直阻塞，相当于死循环，直到客户端停止
                            while ((len = inputStream.read(data)) != -1) {
                                System.out.println(new String(data, 0, len));
                            }
                        } catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }).start();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }).start();

    }
}
